package club.pchome.handler;

import club.pchome.dto.Result;
import club.pchome.ex.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器 参考：http://blog.csdn.net/linxingliang/article/details/51585933
 * http://blog.csdn.net/chinrui/article/details/71036544
 * 
 * @date 2018年12月18日
 * @version 1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * ServletException 异常处理
	 * 
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@ExceptionHandler(ServletException.class)
	public Result<Object> defaultErrorHandler(HttpServletRequest request, ServletException e) throws Exception {
		int code = 0;
		if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
			LOGGER.error("request api:" + request.getRequestURI(), e);
			code = 404;
		} else {
			code = 500;
			LOGGER.error("request api:" + request.getRequestURI(), e);
		}
		return Result.initFailureResult(code, e.getMessage());
	}

	@ResponseBody
	@ExceptionHandler(Exception.class)
	public Result<String> resolveException(HttpServletRequest request, Exception ex) {
		return resolveExceptionHandle(ex, request);
	}

	/**
	 * 异常信息解析方法
	 * 
	 * @param ex
	 * @return 返回解析好的Result，并且可以根据result的messageCode来决定视图页面
	 */
	private Result<String> resolveExceptionHandle(Exception ex, HttpServletRequest request) {
		Result<String> result = null;
		if (ex instanceof ServiceException) {
			result = ((ServiceException) ex).getResult();
			LOGGER.error("result:{}", result);
		} else {
			result = Result.initFailureResult(Result.SYSTEM_ERROR_CORD, "系统异常");
		}
		LOGGER.error("request api:{}. error message:{}. result:{}. ", request.getRequestURL(), ex.getMessage(), result,
				ex);
		return result;
	}
}
